<?php

namespace app\admin\controller\order;

use app\admin\model\Cmdlog;
use app\admin\model\Roomclean;
use app\admin\model\Shop;
use app\admin\model\Shopbalanceprofit;
use app\admin\model\Shopdevice;
use app\admin\model\Shopmno;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproombook;
use app\admin\model\Shoptable;
use app\admin\model\Userallbalance;
use app\admin\model\Userbalance;
use app\admin\model\Userorderprofit;
use app\admin\model\Usertuan;
use app\api\service\VbillService;
use app\common\controller\Backend;
use think\Db;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class Shoptableorder extends Backend
{

    /**
     * Shoptableorder模型对象
     * @var \app\admin\model\Shoptableorder
     */
    protected $model = null;
    protected $noNeedRight = ['open', 'close'];
    protected $searchFields = 'order_no';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Shoptableorder;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->where('Shoptableorder.status', '<>', 'paying')
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {

            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function add($id = null)
    {

        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $order_no = $params['order_no'];
                $shopTableOrderModel = new \app\admin\model\Shoptableorder();
                $order = $shopTableOrderModel->where('order_no', $order_no)->find();
                if ($order['status'] == 'refund') {
                    $this->error("此订单已退款，无需操作");
                }

                if ($order['status'] == 'doing') $this->error("请先结束订单，才能退款");

                $old_refund_amount = $order['refund_amount'];
                if ($order['pay_amount'] > 0) {
                    $refund_amount = $params['refund_amount'];
                    if ($refund_amount > $order['pay_amount']) $this->error("退款金额不能大于订单实付金额");

                    //重组退款金额及收益
                    $shopModel = new Shop();
                    $shop = $shopModel->where('id', $order['shop_id'])->find();
                    $orderAmount = $order['pay_amount'] - $refund_amount;
                    $pay_rate = formatMoney($shop['pay_rate'] * $orderAmount / 100);
                    $rate = formatMoney($shop['ratio'] * $orderAmount / 100);
                    // 退款后，剩余收益
                    $profit = $orderAmount - $pay_rate - $rate;

                    $mnoModel = new Shopmno();
                    $shopMno = $mnoModel->where('shop_id',$order['shop_id'])->find();
                    if(!empty($shopMno) && $shopMno == 100){
                        $mno = $shopMno['mno'];
                    }else{
                        $mno = $this->mno;
                    }
                    $req = array();
                    $req['mno'] = $mno;
                    $req['ordNo'] = getOrderSn();
                    $req['origOrderNo'] = $order['order_no'];
                    $req['amt'] = $refund_amount;

                    $vbillService = new VbillService();
                    $ret = $vbillService->refund($req);
                    $result = json_decode($ret, true);
                    if ($result['code'] != '0000') {
                        $this->error($result['msg']);
                    }
                    if ($result['respData']['bizCode'] != "0000") {
                        $this->error($result['respData']['bizMsg']);
                    }

                    //更新订单收益
                    $shopOrderProfitModel = new Shoporderprofit();
                    if ($profit == 0) {//清除收益表记录
                        $shopOrderProfitModel->where('type', 'order')->where('from', 'tq')->where('order_id', $id)->delete();
                    } else {
                        $shopOrderProfitModel->where('type', 'order')->where('from', 'tq')->where('order_id', $id)->update(['amount' => $profit]);
                    }
                    //更新用户收益
                    $userOrderProfitModel = new Userorderprofit();
                    $userOrderProfitModel->where('type', 'order')->where('order_id', $id)->delete();
                    $old_refund_amount = $old_refund_amount + $refund_amount;
                }

                //如果有余额支付回退余额
                if ($order['balance'] > 0) {

                    //删除店铺支出余额
                    $userBalanceModel = new Userbalance();
                    $userBalanceModel->where('order_id', $order['id'])->where('type', 'out')->delete();

                    //删除平台支出余额
                    $userAllBalance = new Userallbalance();
                    $userAllBalance->where('order_id', $order['id'])->where('type', 'out')->delete();

                    //删除平台商家收益
                    $shopBalanceProfit = new Shopbalanceprofit();
                    $shopBalanceProfit->where('order_id', $order['id'])->where('order_type', 'qp')->delete();

                }

                //如果是团购券 回滚
                if ($order['tuan_id'] != -1) {
                    $userTuanModel = new Usertuan();
                    $userTuanModel->where('id', $order['tuan_id'])->update(['status' => 'unuse']);
                }

//                //判断订单是否使用美团券
//                if (!empty($order['mt_code'])) {
//                    Db::name('user_meituan_code')->where('mt_code', $order['mt_code'])->update(['status' => 'unuse']);
//                }
//
//                //判断订单是否使用抖音券
//                if (!empty($order['dou_code'])) {
//                    Db::name('user_dou_code')->where('dou_code', $order['dou_code'])->update(['status' => 'unuse']);
//                }

                // 更新原订单数据
                $shopTableOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'refund_amount' => $old_refund_amount, 'update_time' => time()]);

                $this->success();

            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    protected function add_test($id = null)//备份
    {

        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                $order_no = $params['order_no'];
                $shopTableOrderModel = new \app\admin\model\Shoptableorder();
                $shopModel = new Shop();
                $order = $shopTableOrderModel->where('order_no', $order_no)->find();
                if ($order['status'] == 'refund') {
                    $this->error("此订单已退款，无需操作");
                }

                $refund_amount = $params['refund_amount'];

                $orderAmount = 0;
                $profit = 0;
                $pay_amount = 0;
                $shop = $shopModel->where('id', $order['shop_id'])->find();

                if ($order['ya_amount'] > 0) {
                    if ($refund_amount > $order['ya_amount']) $this->error("退款金额不能大于订单实付金额");
                    $orderAmount = $order['ya_amount'] - $refund_amount;
                    $pay_amount = $orderAmount;
                    $pay_rate = formatMoney($shop['pay_rate'] * $orderAmount / 100);
                    $rate = formatMoney($shop['ratio'] * $orderAmount / 100);
                    $profit = $orderAmount - $pay_rate - $rate;

                    error_log("===profit===" . $profit);
                } else {
                    if ($refund_amount > $order['balance']) $this->error("退款金额不能大于订单实付金额");
                    $orderAmount = $order['balance'] - $refund_amount;
                }

                $req = array();
                $req['mno'] = $this->mno;
                $req['ordNo'] = getOrderSn();
                $req['origOrderNo'] = $order['order_no'];
                $req['amt'] = $refund_amount;

                if ($order['ya_amount'] > 0) {
                    $vbillService = new VbillService();
                    $ret = $vbillService->refund($req);
                    $result = json_decode($ret, true);
                    if ($result['respData']['bizCode'] != "0000") {
                        $this->error($result['respData']['bizMsg']);
                    }
                }


                $shopTableOrderModel->where('id', $order['id'])->update(['status' => 'refund', 'refund_amount' => $refund_amount, 'update_time' => time(), 'book_end' => time()]);

                $shopOrderProfitModel = new Shoporderprofit();
                $shopProfit = $shopOrderProfitModel->where('type', 'order')->where('from', 'tq')->where('order_id', $id)->find();
                if ($shopProfit) {
                    if ($profit > 0) $shopOrderProfitModel->where('id', $shopProfit['id'])->update(['amount' => $profit]);
                } else {
                    if ($profit > 0) $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                        'user_id' => $shop['user_id'], 'create_time' => time(), 'from' => 'tq', 'amount' => formatMoney($profit)]);
                }
                $userOrderProfitModel = new Userorderprofit();
                $userOrderProfitModel->where('type', 'order')->where('order_id', $id)->delete();


                $shopTableModel = new Shoptable();
                $shopTableModel->where('id', $order['table_id'])->update(['status' => 'free']);

                //如果是余额支付 回滚
                if ($order['balance'] != 0) {
                    $userBalanceModel = new Userbalance();
                    $balance = $userBalanceModel->where('order_id', $order['id'])->where('type', 'out')->where('from', 'tq')->find();
                    if ($balance) {
                        if ($balance['amount'] > $refund_amount) {
                            $userBalanceModel->where('id', $balance['id'])->update(['amount' => $balance['amount'] - $refund_amount]);
                        }

                    }
                }

                $shopTableOrderModel->where('id', $order['id'])->update(['amount' => $orderAmount, 'pay_amount' => $pay_amount]);

                //如果是团购券 回滚
                if ($order['tuan_id'] != -1) {
                    $userTuanModel = new Usertuan();
                    $userTuanModel->where('id', $order['tuan_id'])->update(['status' => 'unuse']);
                }
                $this->success();

            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function open($id = NULL)
    {
        $user = $this->auth->getUserInfo();

        $shopTableOrderModel = new \app\admin\model\Shoptableorder();
        $order = $shopTableOrderModel->where('id', $id)->find();

        if ($order['status'] == 'done' || $order['status'] == 'refund') {
            $this->error("订单状态 不允许开启");
        }


        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('shop_id', $order['shop_id'])->where('device_type', 'tq')->where('room_id', $order['room_id'])->find();

        if ($device['version'] == 2) {
            $sn = $device['sn'];
            $req = array();
            $req['sec'] = $order['min'] * 60;
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $sn;
            $req['voice'] = "欢迎光临，祝您玩的开心";

            $ret = http_post_json($this->cmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
        } else {
            $req = array();
            $req['switchOne'] = 1;
            $req['switchTwo'] = 1;
            $req['door'] = 1;
            $req['hello'] = "您好开台成功祝您玩得开心";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];
            $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }
        }

        $this->success('成功');

    }

    public function edit($id = NULL)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                $order_no = $params['order_no'];
                $time = $params['book_start'];
                $shopOrderModel = new \app\admin\model\Shoptableorder();
                $order = $shopOrderModel->where('order_no', $order_no)->find();
                if ($order['status'] == 'done' || $order['status'] == 'refund') {
                    $this->error("订单状态 不允许修改");
                }
                if ($order['status'] != 'payed') {
                    $this->error("此订单已开始或者已完成，不支持更改");
                }


                $this->success("成功");

            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function close($id = NULL)
    {


        $user = $this->auth->getUserInfo();
        $shopTableOrderModel = new \app\admin\model\Shoptableorder();
        $order = $shopTableOrderModel->where('id', $id)->find();
        if ($order['status'] == 'done') {
            $this->error("此订单已完成，无需操作");
        }
        $deviceModel = new Shopdevice();
        $device = $deviceModel->where('room_id', $order['table_id'])->where('device_type', 'tq')->find();
        $shopTableOrderModel->where('id', $order['id'])->update(['status' => 'done']);

        $tableModel = new Shoptable();
        $tableModel->where('id', $order['table_id'])->update(['status' => 'free']);
        $cmdModel = new Cmdlog();

        $req = array();
        if ($device['version'] == 3) {
            $req['sec'] = 0;
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];
            $req['voice'] = "欢迎下次来玩";

            $ret = http_post_json($this->cmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            $cmdModel->insert(['user_id' => $user['id'], 'cmd' => json_encode($req), 'create_time' => time(), 'shop_id' => $order['shop_id'], 'room_id' => $order['table_id']]);

        } else {
            $req['switchOne'] = 0;
            $req['switchTwo'] = 0;
            $req['door'] = 2;
            $req['hello'] = "欢迎下次来玩";
            $req['orderNo'] = $order['order_no'];
            $req['sn'] = $device['sn'];
            $ret = http_post_json($this->openTqCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);
            if ($ret['code'] == 0) {
                $msg = "正在打开中";
            }
        }


        $this->success('已关闭');

    }
}
